package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.mapper.DatadictMapper;
import com.indusfo.spc.mapper.EquipmentMapper;
import com.indusfo.spc.mapper.StationMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.Equipment;
import com.indusfo.spc.pojo.ProductLine;
import com.indusfo.spc.pojo.Station;
import com.indusfo.spc.service.EquipmentService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 *	 类说明:设备资料业务层实现类
 *
 * @author XIET
 *
 * @version 创建时间：2018年12月3日 上午10:46:56
 */
@Service
public class EquipmentServiceImpl implements EquipmentService {

	private  static  final Logger logger = LoggerFactory.getLogger(EquipmentServiceImpl.class);

	/**
	 * 注入mapper
	 */
	@Resource
	private EquipmentMapper equipmentMapper;
	@Resource
    private StationMapper stationMapper;
	@Resource
	private DatadictMapper tdatadictMapper;
	@Resource
	private UploadMapper uploadMapper;
	/**
	 * 查询设备资料
	 */
	@Override
	public JSONObject queryEquipment(Equipment equipment) {
		//声明listEquipment集合，用来装查询出来的参数
		List<Equipment> listEquipment = null;
        try{


            Integer pagesize = equipment.getPagesize();
            Integer pageindex = equipment.getPageindex();
            if(pagesize != null && pageindex != null) {
                equipment.setIncept(pagesize*(pageindex - 1));
            }

            /*//获取设备资料id
            Integer lEquipmentId = equipment.getLEquipmentId();
            //判断lEquipmentId 是否存在，存在则是查询单个设备资料
            if(lEquipmentId != null) {
            	listEquipment = equipmentMapper.getEquipment(lEquipmentId);
            }else {
            	//lEquipmentId 不存在，则查询所有设备资料
            	listEquipment = equipmentMapper.listEquipment(equipment);
            }*/
            listEquipment = equipmentMapper.listEquipment(equipment);
            //判断查询出来的集合是否为空
            if(listEquipment.isEmpty()) {
                return JSONObject.oK("没有设备资料相关数据", listEquipment, 0);
            }
            //用来记录查询出来的条数
            int count = equipmentMapper.countEquipment(equipment);
            return JSONObject.oK("查询成功", listEquipment, count);
        }catch(GlobalException e){//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
	}

	/**
	 * 删除设备资料
	 */
	@Override
	public JSONObject deleteEquipment(Long[] lEquipmentIds, Integer lDataState) {
		try{
			//判断传入的参数是否为null
			if(lDataState == null) {
				//为null抛出异常
				throw new ParamsErrorException("数据状态不能为空");
			}else if(lDataState != 1 && lDataState != 2 && lDataState != 3) {
	            throw new ParamsErrorException("数据状态错误");
	        }
			if(lEquipmentIds == null) {
				throw new ParamsErrorException("请选择设备资料");
			}
			//调用删除的接口
			int row = equipmentMapper.deleteEquipment(lEquipmentIds,lDataState);
			//声明msg字符串，用来存抛出的异常
			String msg = "";
	        if (row == 0) {
	            // 判断传入的数据状态参数lDataState,返回相应信息
	            switch (lDataState) {
	                case 1:
	                    throw new ModifyFailedException("启用失败");
	                case 2:
	                    throw new ModifyFailedException("删除失败");
	                case 3:
	                    throw new ModifyFailedException("停用失败");
	                default:
	                	break;
	            }
	        } else {
	            switch (lDataState) {
	                case 1:
	                    msg = "启用成功";break;
	                case 2:
	                    msg = "删除成功";break;
	                case 3:
	                    msg = "停用成功";break;
	                default:
	                	break;
	            }
	        }
	        return JSONObject.oK(msg);
		}catch(GlobalException e) {
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 插入设备资料
	 */
	@Override
	public JSONObject insertEquipment(Equipment equipment) {
		try {
			//判断传入的参数是否为null
			if(equipment.getLEquipmentId()!=null) {
				//为null则抛出异常
				throw new ParamsErrorException("新增设备资料时不能有id");
			}
			if(equipment.getVcRemark()==null){
				equipment.setVcRemark("");
			}
			checkParam(equipment);
			checkNoRepeat(equipment);
			/**
			 * @author: louk
			 * @param:
			 * @Return:
			 * @Description: :根据工位Id获取工位的名称
			 * @date: 2019/9/5 13:23
			 *
			 */
            Integer lStationId = equipment.getLStation();
            List<Station> station = stationMapper.getStation(lStationId);
            String staName = station.get(0).getStaName();
            equipment.setLStationName(staName);
            //调用新增接口
			int row = equipmentMapper.insertSelective(equipment);
			if(row == 0) {
				throw new ModifyFailedException("新增设备资料失败");
			}
			return JSONObject.oK("新增成功");
		}catch(GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 修改设备资料
	 */
	@Override
	public JSONObject updateEquipment(Equipment equipment) {
		try {
			//判断传入的参数是否为null
			if(equipment.getLEquipmentId()==null) {
				//为null则抛出异常
				throw new ParamsErrorException("修改设备资料id不能为空");
			}
			if(equipment.getVcRemark()==null){
				equipment.setVcRemark("");
			}
			checkParam(equipment);
			checkNoRepeat(equipment);

			/**
			 * @author: louk
			 * @param:
			 * @Return:
			 * @Description: :根据工位Id获取工位的名称
			 * @date: 2019/9/5 13:23
			 *
			 */
            Integer lStationId = equipment.getLStation();
            List<Station> station = stationMapper.getStation(lStationId);
            if(station==null){
                throw new ModifyFailedException("工位不能为空");
            }
            String staName = station.get(0).getStaName();
            equipment.setLStationName(staName);
			//调用修改的接口
			int row = equipmentMapper.updateByPrimaryKeySelective(equipment);
			if(row == 0) {
				throw new ModifyFailedException("数据修改失败");
			}
			return JSONObject.oK("数据修改成功");
		}catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 查询工位
	 */
	@Override
	public JSONObject queryLStation(Integer lProductionLineId) {
		//声明listLStation集合，用来装查询出来的参数
		List<Integer> listLStation = null;
		try {
			//判断传入的参数是否为null
			if(lProductionLineId==null) {
				//为null则抛出异常
				throw new ParamsErrorException("请输入产线id");
			}
			//调用查询接口
			listLStation = equipmentMapper.listLStation(lProductionLineId);
			//判断查出来的list集合是否为空
			if(listLStation.isEmpty()) {
				//为null则抛出异常
				throw new QueryFailedException("没有相关信息");
			}
			return JSONObject.build(200, "查询成功", listLStation);
		}catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 根据编码查重
	 * @return
	 */
	@Override
	public Equipment getByEquipmentCode(Equipment equipment) {
		return equipmentMapper.getByEquipmentCode(equipment);
	}



	public void checkParam(Equipment equipment){
		if(StringUtils.isEmpty(equipment.getVcEquipmentName())){
			throw new ParamsErrorException("设备名称不能为空");
		}
		if(equipment.getVcEquipmentName().length()>50){
			throw new ParamsErrorException("设备名称长度不能大于50");
		}
		if(StringUtils.isEmpty(equipment.getVcEquipmentCode())){
			throw new ParamsErrorException("设备编码不能为空");
		}
		if(equipment.getVcEquipmentCode().length()>50){
			throw new ParamsErrorException("设备编码长度不能大于50");
		}
		if(getByEquipmentCode(equipment) != null){
			throw new ParamsErrorException("编码已存在");
		}
		if(equipment.getVcRemark().length()>100){
			throw new ParamsErrorException("说明的备注长度不能大于100");
		}
		if(equipment.getType()==null){
			throw new ParamsErrorException("设备类型不能为空");
		}
		if(equipment.getLStation()==null){
			throw new ParamsErrorException("请选择工位");
		}
		if(equipment.getLProductionLineId()==null){
			throw new ParamsErrorException("请选择产线");
		}


	}
	public  void checkNoRepeat(Equipment equipment){
		int count=equipmentMapper.selectByVcEquipmentName(equipment);
		if(count>0){
			throw new ParamsErrorException("设备名称不能重复");
		}
	}

	@Override
	public String checkNoRepeatExcel(Equipment equipment) {
		if(StringUtils.isEmpty(equipment.getVcEquipmentName())){
			return "设备名称不能为空";
		}
		if(equipment.getVcEquipmentName().length()>50){
			return "设备名称长度不能大于50";
		}
		if(StringUtils.isEmpty(equipment.getVcEquipmentCode())){
			return "设备编码不能为空";
		}
		if(equipment.getVcEquipmentCode().length()>50){
			return "设备编码长度不能大于50";
		}
		if(getByEquipmentCode(equipment) != null){
			return "编码已存在";
		}
		int count=equipmentMapper.selectByVcEquipmentName(equipment);
		if(count>0){
			return "设备名称已存在";
		}
		//产线名城
		String vcProductionLineName = equipment.getVcProductionLineName();
		if(vcProductionLineName==null){
			return "产线名称为空";
		}
		//获取所有产线
		Map<String, ProductLine> productLineMap = uploadMapper.queryProductLine();
		if(!productLineMap.containsKey(vcProductionLineName)){
			return "产线名称填写错误/不规范";
		}
		ProductLine productLine = productLineMap.get(vcProductionLineName);
		Integer lProductionLineId = productLine.getLProductionLineId();
		equipment.setLProductionLineId(lProductionLineId);
		//工位名称
		String lStationName = equipment.getLStationName();
		if(lStationName==null){
			return "工位名称为空";
		}
		Map<String, Station> stationMap = uploadMapper.queryStation();
		if(!stationMap.containsKey(lStationName)){
			return "工位名称填写错误/不规范";
		}
		Station station = stationMap.get(lStationName);
		if(!station.getProductionLineId().equals(lProductionLineId)){
			return "填写工位名称不属于所填写的产线";
		}
		equipment.setLStation(station.getStaId());
		//设备类型
		String typeName = equipment.getTypeName();
		Map<String, Datadict> typeTdatadictMap = uploadMapper.queryType(101028);
		if(!typeTdatadictMap.containsKey(typeName)){
			return "类型名称填写不规范/错误";
		}
		Datadict typeTdatadict = typeTdatadictMap.get(typeName);
		equipment.setType(typeTdatadict.getItemId());
		return null;
	}

	@Override
	public JSONObject updateListEquipment(List<Equipment> equipmentList) {
		uploadMapper.updateListEquipment(equipmentList);
		return null;
	}

}
